#pragma once
#include <iostream>
#include <string>
#include <set>
#include <cstring>
#include <cstdio>
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace log_ns;

class Command
{
private:
public:
    Command()
    {
        // 白名单
        _safe_command.insert("ls");
        _safe_command.insert("touch"); // touch filename
        _safe_command.insert("pwd");
        _safe_command.insert("whoami");
        _safe_command.insert("which"); // which pwd
    }

    ~Command() {}

    bool SafeCheck(const std::string &cmdstr)
    {

        for (auto &cmd : _safe_command)
        {
            if (strncmp(cmd.c_str(), cmdstr.c_str(), cmd.size()) == 0)
            {
                return true;
            }
        }
        return false;
    }

    std::string Excute(const std::string &cmdstr)
    {
        if (!SafeCheck(cmdstr))
        {
            return "Unsafe";
        }
        std::string result;
        FILE *fp = popen(cmdstr.c_str(), "r");
        if (fp)
        {
            char line[1024];
            while (fgets(line, sizeof(line), fp))
            {
                result += line;
            }
            return result.empty() ? "success" : result;
        }
        return "excute error\n";
    }
    void HandlerCommand(int sockfd, InetAddr addr)
    {
        while (true)
        {
            // 接收指令
            char commandbuff[1024];
            ssize_t n = recv(sockfd, commandbuff, sizeof(commandbuff), 0);
            if (n > 0)
            {
                commandbuff[n] = 0;
                LOG(INFO, "get cmd from client ,cmd is %s\n", commandbuff);
                // 回响
                std::string echo_message = Excute(commandbuff);
                send(sockfd, echo_message.c_str(), echo_message.size(), 0);
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error: %s\n", addr.AddrStr().c_str());
                break;
            }
        }
        close(sockfd);
    }

private:
    std::set<string> _safe_command;
};